import { createStore } from "vuex";
import appStore from "./appStore.js";
import { apiBizMessageMsgNums } from '@/api/message';
import {
  setTabBarBadge
} from '@/utils/index'

export default createStore({
  state: {
    //用户信息
    userInfo: {},
    access_token: "",
    refresh_token: "",
    patrol_line_detail: {},
    message_numbers: '', // 未读消息数量
  },
  getters: {
    // 获取用户信息
    GET_USER_INFO(state) {
      return uni.getStorageSync("USER_INFO") || state.userInfo;
    },
    // 获取 ACCESS TOKEN
    GET_ACCESS_TOKEN(state) {
      return uni.getStorageSync("ACCESS_TOKEN") || state.access_token;
    },
    // 获取 REFRESH TOKEN
    GET_REFRESH_TOKEN(state) {
      return uni.getStorageSync("REFRESH_TOKEN") || state.refresh_token;
    },
    // 获取 patrol_line_detail
    GET_PATROL_LINE_DETAIL(state) {
      return uni.getStorageSync("PATROL_LINE_DETAIL") || state.patrol_line_detail;
    },
    // 获取 message_numbers
    GET_MESSAGE_NUMBERS(state) {
      return uni.getStorageSync("MESSAGE_NUMBERS") || state.message_numbers;
    }
  },
  mutations: {
    // 更新用户信息
    SET_USER_INFO(state, data) {
      // 保存到本地
      uni.setStorageSync("USER_INFO", data);
      state.userInfo = data;
    },
    // 更新ACCESS TOKEN
    SET_ACCESS_TOKEN(state, data) {
      // 保存到本地
      uni.setStorageSync("ACCESS_TOKEN", data);
      state.access_token = data;
    },
    // 更新REFRESH TOKEN
    SET_REFRESH_TOKEN(state, data) {
      // 保存到本地
      uni.setStorageSync("REFRESH_TOKEN", data);
      state.refresh_token = data;
    },
    // 更新 patrol_line_detail
    SET_PATROL_LINE_DETAIL(state, data) {
      // 保存到本地
      uni.setStorageSync("PATROL_LINE_DETAIL", data);
      state.patrol_line_detail = data;
    },
    // 获取 message_numbers
    SET_MESSAGE_NUMBERS(state, data) {
      state.message_numbers = data;
    }
  },
  actions: {
    // 通过单点登陆获取用户信息
    setUserInfo({ state, commit }, data) {
      commit("SET_USER_INFO", data);
    },
    setAccessToken({ state, commit }, data) {
      commit("SET_ACCESS_TOKEN", data);
    },
    setRefreshToken({ state, commit }, data) {
      commit("SET_REFRESH_TOKEN", data);
    },
    // 更新 patrol_line_detail
    setPatrolLineDetail({ state, commit }, data) {
      commit("SET_PATROL_LINE_DETAIL", data);
    },
    // 更新未读消息数量
    setMessageNumbers({ state, commit }, data) {
      apiBizMessageMsgNums().then(res => {
        uni.setStorageSync("MESSAGE_NUMBERS", res);
        console.log('MESSAGE_NUMBERS', res);
        setTabBarBadge();
        commit("SET_MESSAGE_NUMBERS", res);
      })
    }
  },
  modules: {
    appStore,
  },
});
